package com.ceshi.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ceshi.pojo.Result;
import com.ceshi.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class Logincheck implements HandlerInterceptor {
    @Override//运行前执行
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        System.out.println ("aaaaaaaaaaaa");

        String url = req.getRequestURI ().toString ();
        log.info ("请求的url", url);
        if (url.contains ("login")) {
            log.info ("登录操作");
            // filterChain.doFilter (servletRequest,servletResponse);
            return true;
        }
        String jwt = req.getHeader ("token");
        if (!StringUtils.hasLength (jwt)) {
            log.info ("为空");
            Result error = Result.error ("cuowu");
            String not = JSONObject.toJSONString (error);
            resp.getWriter ().write (not);
            return false;
        }
        try {
            JwtUtils.parseJWT (jwt);
        } catch (Exception e) {
            e.printStackTrace ();
            log.info ("解析令牌失败");
            Result error = Result.error ("cuowu");
            String not = JSONObject.toJSONString (error);
            resp.getWriter ().write (not);
            return false;
        }
        log.info ("合法，放行");
        // filterChain.doFilter (servletRequest, servletResponse);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println ("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb");

    }

    @Override//视图渲染完成后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println ("cccccccccccccccccccccccccccccc");
        // HandlerInterceptor.super.afterCompletion (request, response, handler, ex);
    }
}
